package com.yonyou.pmclouds.license;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.iuap.tenant.sdk.TenantCenter;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.util.DateUtils;
import com.yonyou.pmclouds.job.AbstractJobExecutor;
import com.yonyou.pmclouds.job.ExecResult;
import com.yonyou.pmclouds.job.JobExecutor;
import com.yonyou.pmclouds.productactive.entity.EffectBuziInfoVO;
import com.yonyou.pmclouds.productactive.rmiitf.LicenseQuery;
import com.yonyou.pmclouds.productactive.rmiitf.ProductActiveRemoteService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@JobExecutor("updateLicense")
public class UpdateLicenseJob extends AbstractJobExecutor {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private LicenseQuery licenseQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProductActiveRemoteService service;

    @Override
    public ExecResult<String> execute(String param) throws Exception {
        StringBuilder info = new StringBuilder();
        // 获取上一次更新的日期
        Date date = licenseQuery.queryLastLicenseUpdateDate();
        if (date == null) {
            date = new Date();
        }
        Date now = new Date();
        // 查询需要更新授权的租户
        EffectBuziInfoVO[] effectBuziInfoVOS
                = licenseQuery.queryTenantOrderEffectInDays(DateUtils.asDateBegin(date), DateUtils.asDateEnd(now), now);
        if (ArrayUtils.isEmpty(effectBuziInfoVOS)) {
            return ExecResult.SUCCESS;
        }
        // 调用应用中心更新授权人数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (EffectBuziInfoVO buziInfo : effectBuziInfoVOS) {
            try {
                TenantCenter.addAndActiveAndAuthNum(buziInfo.getPkTenant(), ApplicationConsts.APPLICATION_ID, null,
                        sdf.format(buziInfo.getEndDate()), buziInfo.getAccountQuantity());
            } catch (Exception ex) {
                // 平台更新失败，则记录日志
                logger.log(ex);
                info.append(buziInfo.getPkTenant()).append(",");
            }
        }
        if (info.length() == 0) {
            info.append("ok");
        }
        service.insertLastUpdateLicenseInfo(now, info.toString());
        return ExecResult.SUCCESS;
    }
}
